\chapter{Matrices}
\index{matricies|(}

This chapter is an introduction to the matrix data type.  Matrices
are the most commonly used data type in \RLaB\, and there are many
powerful operations and functions you can perform on them.  A matrix
is generally a two dimensional array of scalars, although \RLaB\ also
supports string matrices, see Chapter ~\ref{chap-strings}.  All
numeric operations and functions work for any combination of
real and complex operands or arguments.

The elements inside a matrix are refered to by the number of the row and
column they are in.  Rows are specified first and go across, and are
numbered from top to bottom. Columns go down, and are numbered from
left to right.  
  
\section{Matrix Creation}

The \verb+[+ and \verb+]+ operators are used to create and access
a matrix.  For example, to create a matrix at the command line, you would
just type: 

\begin{verbatim}
> m = [ 1, 2, 3; 4, 5, 6; 7, 8, 9 ]
 m =
 matrix columns 1 thru 3
        1          2          3  
        4          5          6  
        7          8          9  
\end{verbatim}

The rows of the matrix are delimited with `\verb+;+' and the elements
of each row are delimited with `\verb+,+'. If you want a complex matrix
you enter it using the normal notation of real and imaginary parts.
Here is an example:

\begin{verbatim}
> z= [ 1+2i, 2+3j, 3 + 4i;
>      4 -5i, -5+6j, -6 -7j ]
 z =
 matrix columns 1 thru 3
                  1 + 2i                  2 + 3i                  3 + 4i
                  4 - 5i                 -5 + 6i                 -6 - 7i
\end{verbatim}

This example shows a few things that are pretty important.  You can
use either \verb+i+ or \verb+j+, but you can't leave spaces between
the imaginary part and the letter.  Spaces are generally fine
everywhere else.

While the previous method for matrix creation is quite convenient,
often you will need specific types of matrices, such as an identity
matrix, a matrix of random values, or a Hilbert matrix. There are
\RLaB\ functions  to produce these and many other types of matrices.
All functions are described in Chapter~\ref{chap-refmain}, however those
that are likely to be of particular interest for creating matrices are:
\begin{description}
\item[compan] generates the companion matrix of its argument
\item[diag] diagonalises its argument
\item[eye] produces an identity matrix
\item[hilb] produces a Hilbert matrix
\item[linspace and logspace] produce spaced vectors
\item[ones] produce a matrix with all elements $1$.
\item[rand] generates random matrix
\item[reshape] changes the structure of a matrix
\item[zeros] produce a matrix with all elements $0$.
\end{description}

Another useful method for creating a matrix is to read the values
from a file. \RLaB\ provides several ways of doing this. The
two most popular are \verb+readm()+ and \verb+read()+.

\verb+read()+ reads a matrix that has been written with the
\RLaB\ \verb+write()+ function  (See Section~\ref{fn:read}
and Section~\ref{fn:write}). Here is a contrived example - you would
normally \verb+write+ it out in one session, and \verb+read+ it again
in a later session. You should also realise that \verb+read+ and
\verb+write+ are not restricted to a storing and retrieving a single
variable, or even a single type of variable, in a file.  You can store
several different types of variables in each file, according to your
needs.

\begin{verbatim}
> z = [ 3 , 4; -4-3j , 786 ] 
 z =
                  3 + 0i                  4 + 0i
                 -4 - 3i                786 + 0i
> who()
eps  pi   z              
> write( "save_z.dat" , z )
        1
> // We have now written out the matrix `z' to the file `save_z.dat'
> clear(z);
> who()
eps  pi                  
> // The matrix `z' is now gone from the symbol table
> read( "save_z.dat" )
        1
> who()
eps  pi   z              
> // And now it has been read back in.
> diary()
\end{verbatim}

\verb+readm()+ (See Section~\ref{fn:readm}) reads a text file
that contains white-space separated columns of numbers.  This is
useful if you are trying to use the output of other programs.  If you
want to, you can also write out a matrix in the same format, using the
\verb+writem+ function.
If you don't like the way the matrix is organised, the 
\verb+reshape()+ function (See Section~\ref{fn:reshape})
is a good way to restructure it. 

\begin{verbatim}
> a = [ 1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
 a =
        1          2          3          4  
        5          6          7          8  
        9         10         11         12  
> // Now we write the matrix to a file.
> writem("matrix_text", a)
        1
> clear(a)
        1
> who()
eps  pi                  
> // And get it back - store it in a different variable this time
> b = readm("matrix_text")
 b =
        1          2          3          4  
        5          6          7          8  
        9         10         11         12  
> // But we want those elements organised as two rows and six columns
> c = reshape(b, 2,6)
 c =
 matrix columns 1 thru 6
        1          9          6          3         11          8  
        5          2         10          7          4         12  
\end{verbatim}

It appears that things have gone horribly wrong in that last example.
However this is expected behavior. The matrix is stored column by
column, and if you run down each column in each matrix, the order is
the same in each matrix.  The transposition operator might come in
handy if you want it to work by rows, as shown here:
\begin{verbatim}
> d = reshape(b', 2,6)
 d =
 matrix columns 1 thru 6
        1          3          5          7          9         11  
        2          4          6          8         10         12  
> e = (reshape(b',6,2))'
 e =
 matrix columns 1 thru 6
        1          2          3          4          5          6  
        7          8          9         10         11         12  
\end{verbatim}


Sometimes when you have a problem that is represented as two matrices,
you would like to combine them to make a single matrix.  This is a
pretty simple task as soon as you realise that there is nothing that
makes the things inside the square brackets have to be scalars ---
they can also be strings and other matricies.  We will look at using
matricies here, and deal with strings later.

When trying to tack several matricies together to make a new matrix,
or using a combination of scalars and matricies to make a new matrix,
you should think of the matricies as being equivalent to how they
would be represented if you had to type them yourself.  So imagine
that each row is terminated with a semicolon and each element
seperated by a comma.  Then fill in commas and semicolons between the
elements to make up the new matrix.  Here are some examples:

\begin{verbatim}
> a = [1, 2,3; 4,5,6]
 a =
        1          2          3  
        4          5          6  
> b = [ 7, 8, 9; 10, 11, 12]
 b =
        7          8          9  
       10         11         12  
> c = [a,b]
 c =
 matrix columns 1 thru 6
        1          2          3          7          8          9  
        4          5          6         10         11         12  
> d = [a;b]
 d =
        1          2          3  
        4          5          6  
        7          8          9  
       10         11         12  
> e = [ -2, -1 ,0; a]
 e =
       -2         -1          0  
        1          2          3  
        4          5          6  
\end{verbatim}

\section{Vector Creation}
\index{vectors}
Although there is no distinct vector type in \RLaB , you can
pretend that there is. If your algorithm or program does not need
two dimensional arrays, then you can use matrices as one dimensioned
arrays.

When using vectors, or single dimension arrays, row matrices are
created. The simplest way to create a vector is with the `\verb+:+'
operator(s): 
\begin{rail}
Vector: start ':' end ( ':' increment ) ?;
\end{rail}

The first operand specifies the starting value, the second operand
specifies the last value. The optional third operand can be used to
specify an increment. If this is not specified, the default
increment is 1. Here are some examples:

\begin{verbatim}
> c = 1:4
 c =
        1          2          3          4  
> d = 1:3:0.5
 d =
        1        1.5          2        2.5          3  
> e = 1:3:0.6
 e =
        1        1.6        2.2        2.8  
\end{verbatim}

The other way to generate a vector is to simply specify it using the
matrix form with one of the dimensions set to $1$.  This method allows
you to generate a vector containing any elements, not just an evenly
spaced sequence.  Just remember that \RLaB\ doesn't know anything
about vectors --- they are just a matrix where one of the dimensions
is $1$.  Some functions do something slightly different if they come
across a matrix that is the vector form, but they are really just a
notational convenience, not a fundamental change, and anything that
applies to a matrix also applies to something that we treat as a
vector.

\section{Matrix Attributes}
\index{matrix!attributes}
\index{attributes of a matrix}

The attributes of a matrix, such as how many rows it has, are
accessible in several ways. All attributes are accesible through
function calls, for example:

\begin{verbatim}
> my_matrix = [ 1, 0.333, 0.367, 0.24;
>               6, -0.3, 0.9, 3];
> show(my_matrix)
   name:      my_matrix  
   class:     num        
   type:      real       
     nr:      2          
     nc:      4          
> size(my_matrix)
        2          4  
> length(my_matrix)
        4
> class(my_matrix)
num
> type(my_matrix)
real
> name(my_matrix)
my_matrix
\end{verbatim}

You can learn more about each of those functions by refering to the
Function Reference, or by using the on-line help.

Matrix attributes are also accessible via a shorthand notation:

\begin{verbatim}
> // Number of rows
> my_matrix.nr
        2
> // Number of columns
> my_matrix.nc
        4
> // Number of elements
> my_matrix.n
       8
> // Class of variable
> my_matrix.class
num
> // Type of contents
> my_matrix.type
real
\end{verbatim}

\section{Referencing a Matrix}

It doesn't matter how a matrix was created - using the vector or matrix 
methods, there are two ways to access it. You can either specify an 
row and column, or you can specify a particular element. For example:

\begin{verbatim}
> a = rand(3,4)
 a =
 matrix columns 1 thru 4
        1      0.333      0.665      0.167  
    0.975     0.0369     0.0847      0.655  
    0.647      0.162      0.204      0.129  
> a[1,4]
    0.167
> a[4]
    0.333
> v = 1:4
 v =
 matrix columns 1 thru 4
        1          2          3          4  
> v[1;3]
        3
> v[2]
        2
\end{verbatim}

As you can see, matrices are stored internally in a column-wise
fashion. To force a matrix to it's internal form you can use the
`\verb+[:]+' operator:

\begin{verbatim}
> a = rand(2,3)
 a =
 matrix columns 1 thru 3
        1      0.647     0.0369  
    0.975      0.333      0.162  
> a [ : ]
 matrix columns 1 thru 1
        1  
    0.975  
    0.647  
    0.333  
   0.0369  
    0.162  
\end{verbatim}

In addition to accessing single elements, we can also access partial
rows and/or columns of a matrix. We use the `\verb+;+' symbol to
delimit row and column indicies, and the `\verb+,+' symbol to delimit
individual row or column indicies.
To reference an entire row or column, we leave out the column or
row index respectively:

\begin{verbatim}
> g = rand(3,4)
 g =
        1      0.333      0.665      0.167  
    0.975     0.0369     0.0847      0.655  
    0.647      0.162      0.204      0.129  
> g[3;]
    0.647      0.162      0.204      0.129  
> g[;2]
    0.333  
   0.0369  
    0.162  
\end{verbatim}

To reference a sub-matrix, we just specify which rows and columns are
to be extracted:

\begin{verbatim}
> g[2; 3,4]
   0.0847      0.655  
\end{verbatim}

As stated previously, any expression that evaluates to a matrix can
have it's elements referenced. For example, the \verb+size()+ function
returns a two element matrix, where the first element contains the 
number of rows in the argument, and the second element contains the
number of columns. For example:

\begin{verbatim}
> size(g)[2]
        4
\end{verbatim}


\section{Assignment}

Just as we can read from parts of a matrix, we can also write to part
of a matrix.  You have seen assignment of a whole matrix to a variable
in previous examples --- now lets look at partial assignment. We can 
re-assign single elements, or groups of elements. For single elements,
we just specify a reference to that element (either row and column or 
vector notation --- it doesn't matter), and equate it to the new value.
For a group of elements, we have to specify a range, and equate that to
a matrix of equal size. Here are some examples:

\begin{verbatim}
> yellow = rand(3,3)
 yellow =
    0.167       0.91      0.265  
    0.655      0.112        0.7  
    0.129      0.299       0.95  
> yellow[2;2] = 967
 yellow =
    0.167       0.91      0.265  
    0.655        967        0.7  
    0.129      0.299       0.95  
> yellow[2,3;1,2] = [100, 200; 300, 400]
 yellow =
    0.167       0.91      0.265  
      100        200        0.7  
      300        400       0.95  
\end{verbatim}
  
\section{Matrix Operations}

The usual mathematical operators ( eg. \verb|+, -, *, /| )  operate on
matrices as well as scalars. Lets look at the various binary operations, 
for \verb+A binop B+:

   \begin{description}
     \item[+] Does element-by-element addition of two matrices.
              The row and column dimensions of \verb+A+ and
              \verb+B+ must be the same, unless either \verb+A+ or
              \verb+B+ is a 1-by-1 matrix; in this case a
              scalar-matrix addition operation is performed.

     \item[--] Does element-by-element subtraction of two matrices.
              The row and column dimensions of both \verb+A+ and
              \verb+B+ must be the same, unless either \verb+A+ or
              \verb+B+ is a 1-by-1 matrix; in this case a
              scalar-matrix subtraction operation is performed.

     \item[*] Performs matrix multiplication on the two
              operands.  The column dimension of {\verb+A+} must match
              the row dimension of {\verb+B+}, unless either \verb+A+ or
              \verb+B+ is a 1-by-1 matrix; in this case a
              scalar-matrix multiplication is performed.

     \item[/] Performs matrix ``right-division'' on it's operands.
              The matrix right-division (\verb+A/B+) can be thought of
              as {\verb+A*inv (B)+}. The column dimensions of \verb+A+
              and \verb+B+ must be the same. Internally right division
              is the same as ``left-division'' with the arguments
              transposed. 

                \[ A / B = ( B^T \setminus A^T )^T \]

              The exception to this dimension rule
              occurs when \verb+B+ is a 1-by-1 matrix; in this case a
              matrix-scalar divide occurs.

   \end{description}

Additionally, \RLaB\ has several other operators that function on
matrix operand(s). 

   \begin{description}
     \item[.*] Performs element-by-element multiplication on
              it's operands. The operands must have the same row and
              column dimensions, unless either \verb+A+ or \verb+B+ is
              a 1-by-1 matrix.

     \item[./] Performs element-by-element division on it's
              operands. The operands must have the same row and column
              dimensions, unless either \verb+A+ or \verb+B+ is a
              1-by-1 matrix.

     \item[$\setminus$] Performs matrix ``left-division''. Given
              operands {\verb+A\B+}, matrix left division is the
              solution to the set of equations $Ax = B$. If $B$ has
              several columns, then each column of $x$ is a solution
              to {\verb+A*x[;i] = B[;i]+}. The row dimensions of
              \verb+A+ and \verb+B+ must agree.

     \item[$.\setminus$] Performs element-by-element left-division.
              Element-by-element left-division is provided for
              symmetry, and is equivalent to \verb+B./A+. The row and
              column dimensions of \verb+A+ and \verb+B+ must agree,
              unless either one is a 1-by-1 matrix.

     \item[${}^\wedge{}$] {\verb+A^B+} raises \verb+A+ to the \verb+B+
              power. When \verb+A+ is a matrix, and \verb+B+ is an
              integer scalar, the operation is performed by successive
              multiplications. When \verb+B+ is not an integer, then
              the operation is performed using \verb+A+'s eigenvalues
              and eigenvectors. The operation is not allowed if
              \verb+B+ is a matrix.

     \item[${.}^\wedge{}$] {\verb+A.^B+} raises \verb+A+ to the
              \verb+B+ power in an element-by-element fashion. Either
              \verb+A+ or \verb+B+ can be matrix or scalar. If both
              \verb+A+ and \verb+B+ are matrices, then the row and
              column dimensions must agree.

     \item['] This unary operator performs the matrix transpose
              operation. \verb+A'+ swaps the rows and columns of A.
              For a matrix with complex elements a complex conjugate
              transpose is performed.

     \item[.'] This unary operator performs the matrix
              transpose operation. \verb+A.'+ swaps the rows and
              columns of A.  The difference between \verb+'+ and
              \verb+.'+ is only apparent when \verb+A+ is a complex
              matrix; then \verb+A.'+ does not perform a complex
              conjugate transpose.

   \end{description}

 There are several details that are very important to note:

   \begin{itemize}

     \item The operators that are denoted by two symbol should not
           have any white space or any other character between the
           two symbols.

     \item The expression \verb+2./A+ is {\bf not} interpreted as
           \verb+2. /A+. \RLaB\ is smart enough to group the period with
           the \verb+/+.

   \end{itemize}

\section{Matrix Relational Operations}

Just as we can perform relational operations on scalars, we can also
do matrix relational operations. When we do a relational test on
two matrices, such as \verb+A == B+, the operands must be the same
dimensions, or one of them must be a 1-by-1 matrix.  The result of
a matrix relational test is a matrix the same size as the operands
filled with ones and zeros according to the result of an
element-by-element test. A one in a particular location means the
test was true for the pair of elements in those locations in the 
operands. For example:

\begin{verbatim}
> a = [1, 2, 3; 4, 5, 6; 7, 8, 9]
 a =
 matrix columns 1 thru 3
        1          2          3  
        4          5          6  
        7          8          9  
> b = a'
 b =
 matrix columns 1 thru 3
        1          4          7  
        2          5          8  
        3          6          9  
> a == b
 matrix columns 1 thru 3
        1          0          0  
        0          1          0  
        0          0          1  
> a >= 5
 matrix columns 1 thru 3
        0          0          0  
        0          1          1  
        1          1          1  
\end{verbatim}

\RLaB\ if-tests do not accept matrices. The \verb+any()+ and
\verb+all()+ functions can be used in combination with relational
and logical tests to conditionally execute statements based upon
matrix properties. 

The function \verb+any()+ returns true if any of the elements of
it's argument are non-zero. The function \verb+all()+ returns true
if all of the elements of it's argument are non-zero.  The \verb+any()+
function is called on the output of another \verb+any()+ call because the
\verb+any()+ function returns a vector when passed a matrix that is not
already a vector.  

\section{Functions}

You have already seen some of the functions in use.  There are for
basic types of functions that can operate on matricies in \RLaB\. They
are: 
   \begin{description}

     \item[Scalar Functions:] These functions operate on scalars, and
           treat matrices in an element-by-element fashion. Some
           examples are:

           \begin{tabbing}
             function1 \= function2 \= function2 \= function4 \kill        
             abs \> exp \> floor \> round \\
             cos \> sin \> tan \> ceil \\
             sqrt \> real \> imag \> conj \\
             isnan \> int \> \> \\
           \end{tabbing}

     \item[Vector Functions:] These functions operate on vectors,
           either row-vectors (1-by-$n$) or column vectors ($m$-by-1),
           in the same fashion.  If the argument is a matrix with both
           dimensions $> 1$ then the operation is performed in a
           column-wise fashion. Some examples are: 

           \begin{tabbing}
             function1 \= function2 \= function2 \= function4 \kill        
             sum \> prod \> mean \> max \\
             min \> fft \> sort \> any \\
           \end{tabbing}

           When using a vector oriented function, like \verb+max()+,
           on a general matrix, it is possible to obtain scalar
           quantities. For example the maximum value in a matrix can
           be obtained using \verb+max (max (a))+. The first call to
           \verb+max()+ returns a vector of the maximum values from
           each column, and the second call to \verb+max()+ returns
           the maximum value in the matrix.  

     \item[Matrix Functions:] These functions operate on matrices as a
           single entity. Some examples are:

           \begin{tabbing}
             function1 \= function2 \= function2 \= function4 \kill        
             balance \> chol \> det \> eig \\
             hess \> inv \> lu \> norm \\
             pinv \> qr \> rank \> rcond \\
             reshape \> solve \> svd \> symm \\
           \end{tabbing}

   \end{description}


\index{matricies|)}





